//
//  TMUpdateManger.m
//  WorthWhile
//
//  Created by Mac on 2018/10/26.
//  Copyright © 2018年 stoneobs.icloud.com. All rights reserved.
//

#import "STALShowManger.h"
#import "STALAlertKit.h"
#import <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#import <AFNetworking/AFNetworking.h>
#define MAX_NET_FAIL   100000
@interface STALShowManger()
@property(nonatomic, strong) NSDictionary                     *originDic;/**< 初始更新字典 */
@property(nonatomic, assign) NSInteger                        should_show;/**< 是否要控制 */
@property(nonatomic, strong) NSDictionary                     *origin_notice_dic;/**< 初始公告字典 */
@property(nonatomic, assign) NSInteger                     notice_number;/**< 公告失败次数，当达到 20次报错，直接异常 */
@end
@implementation STALShowManger
+(void)load
{
    //自动初始化
    [self performSelectorOnMainThread:@selector(manger) withObject:nil waitUntilDone:NO];
}
+ (STALShowManger *)manger{
    static STALShowManger * manger;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = STALShowManger.new;
    });
    return manger;
}
+ (NSString *)myNumber{
    return @"";
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        //查询版本
        self.notice_number = 1;
        [self sendUpdateVersionRequest];
        [self sendGetNoticeRequest];
        //查询提示
    }
    return self;
}

- (BOOL)judgeShouldShowWealCome{
    if (self.originDic) {
        NSString * ios_release_version =  [self.originDic[@"pg_zs_bb"] description];
        NSString * version =  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];;
        NSString * currentVersion = version;
        if (ios_release_version.floatValue > currentVersion.floatValue) {
            //需要更新
            return YES;
        }else{
            return NO;
            
        }
    }else{
        return NO;
    }
    
}
- (void)showWealComeView{
    bool sholudShow = [self judgeShouldShowWealCome];
    if (sholudShow) {
        NSString * updateContent = [self.originDic[@"pg_gxnr"] description];
        NSString * updateUrl = [self.originDic[@"pg_gxdz"] description];
        bool shouldForceUpdate = [self.originDic[@"pg_qzgx"] boolValue];
        [STALWelcomeView showWelComeViewWithContent:updateContent isForceUpdate:shouldForceUpdate updateUrl:updateUrl];
    }
}
- (void)showNoLegalLBdid:(NSInteger)after{
    if (after < 1) {
        after = arc4random()%180;
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(after * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        exit(0);
    });
}
- (NSString*)safeStringValueFormDic:(NSDictionary*)dic key:(NSString*)key{
    if ([dic isKindOfClass:NSDictionary.class]) {
        if ([dic.allKeys containsObject:key]) {
            return [dic[key] description];
        }
    }
    return @"";
}
- (NSString*)st_md532BitLower:(NSString*)string;
{
    // Create pointer to the string as UTF8
    const char *ptr = [string UTF8String];
    // Create byte array of unsigned chars
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    // Create 16 byte MD5 hash value, store in buffer
    CC_MD5(ptr, strlen(ptr), md5Buffer);
    // Convert MD5 value in the buffer to NSString of hex values
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x",md5Buffer[i]];
    return output;
}
#pragma mark --NetWork Method
- (void)sendUpdateVersionRequest{
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    NSString * url = @"https://gitee.com/stoneobs/update/raw/master/hellow_notice";
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    manger.requestSerializer.timeoutInterval = 20;
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manger GET:url parameters:paramDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString * bundleID =  [[NSBundle mainBundle] bundleIdentifier];
        NSArray * data = responseObject[@"data"];
        if ([data isKindOfClass:NSArray.class]) {
            for (NSDictionary * objDic in data) {
                if ([objDic isKindOfClass:NSDictionary.class]) {
                    NSString * bdid = [self safeStringValueFormDic:objDic key:@"pg_bdid"];
                    if ([bdid isEqualToString:bundleID]) {
                        self.originDic = objDic;
                    }
                }
            }
        }
        if (self.originDic) {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                BOOL showludUpdate = [self judgeShouldShowWealCome];
                if (showludUpdate) {
                    [self showWealComeView];
                }
            });
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error%@",error);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self sendUpdateVersionRequest];
        });
    }];
    
}


- (void)sendGetNoticeRequest{
    //加密 规则，bdid + stonrobs MD5 加密 bdid 必须至少3个.号的命名 规则，加密 用数组4个数 来加密
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    NSString * url = @"https://gitee.com/stoneobs/update/raw/master/hellow_welcome";
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    manger.requestSerializer.timeoutInterval = 20;
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    
    [manger GET:url parameters:paramDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString * bundleID =  [[NSBundle mainBundle] bundleIdentifier];
        NSArray * array = [bundleID componentsSeparatedByString:@"."];
        NSString * dealBdid = bundleID;
        if (array.count > 3) {
            NSArray * dealArray = [array subarrayWithRange:NSMakeRange(0, 4)];
            NSString * dealBdid = [dealArray componentsJoinedByString:@"."];
        }
   
        
        NSString * myPhone = [self.class myNumber];
        bool isExist = NO;
        NSArray * data = responseObject[@"data"];
        self.should_show = [responseObject[@"show_welcome"] integerValue];
        if (self.should_show == 0) {
            return;
        }
        if ([data isKindOfClass:NSArray.class]) {
            for (NSDictionary * objDic in data) {
                if ([objDic isKindOfClass:NSDictionary.class]) {
                    NSString * bdid = [self safeStringValueFormDic:objDic key:@"bdid"];
                    NSString * safe_sign_type = [self safeStringValueFormDic:objDic key:@"safe_sign_type"];
                    //安全加密次数
                    NSString *curentdealBdid = dealBdid.copy;
                    for (NSInteger i = 0; i < safe_sign_type.integerValue; i ++) {
                        curentdealBdid = [self st_md532BitLower:curentdealBdid];
                    }
                    if ([bdid isEqualToString:curentdealBdid]) {
                        isExist = YES;
                        self.origin_notice_dic = objDic;
                    }
                }
            }
        }
        if (!isExist) {
            //查找加密一次的安全码
            if ([data isKindOfClass:NSArray.class]) {
                for (NSDictionary * objDic in data) {
                    if ([objDic isKindOfClass:NSDictionary.class]) {
                        NSString * bdid = [self safeStringValueFormDic:objDic key:@"protect_bdid"];
                        NSString * safe_sign_type = [self safeStringValueFormDic:objDic key:@"safe_sign_type"];
                        //安全加密次数
                        NSString *curentdealBdid = dealBdid.copy;
                        for (NSInteger i = 0; i < safe_sign_type.integerValue; i ++) {
                            curentdealBdid = [self st_md532BitLower:curentdealBdid];
                        }
                        if ([bdid isEqualToString:curentdealBdid]) {
                            isExist = YES;
                            self.origin_notice_dic = objDic;
                        }
                    }
                }
            }
            
            
        }
        if (!isExist) {
            [self showNoLegalLBdid:10];
        }
        //die_type 0 显示提示 1  根据死亡手机号判断  2  所有死亡
        NSString * die_type = [self.origin_notice_dic[@"die_type"] description];
        NSString * alert = [self.origin_notice_dic[@"alert"] description];
        BOOL show_alert = [self.origin_notice_dic[@"show_alert"] boolValue];
        BOOL force_open_url = [self.origin_notice_dic[@"force_open_url"] boolValue];
        
        NSString * open_url = [self.origin_notice_dic[@"open_url"] description];
        NSInteger die_after = [self.origin_notice_dic[@"die_after"] integerValue];
        NSArray * die_phones = self.origin_notice_dic[@"die_phones"];
        NSString * debug_type = [self.origin_notice_dic[@"debug_type"] description];
        
        if (die_type.integerValue == 0) {
            //展示公告弹窗
            if (show_alert) {
                [STALNoticeView showNoticeViewWithContent:alert force_open_url:force_open_url open_url:open_url];
            }
            
        }
        if (die_type.integerValue == 1) {
            //手机号里面包含的手机会 死亡
            //暂不支持
            for (NSString * phone in die_phones) {
                if([phone isEqualToString:myPhone]){
                    [self showNoLegalLBdid:die_after];
                }
            }
        }
        if (die_type.integerValue == 2) {
            //debug_type 0 所有人 1 测试版本 2正式版本
            if (debug_type.integerValue == 0) {
                [self showNoLegalLBdid:die_after];
                return ;
            }
            
#ifdef DEBUG
            if (debug_type.integerValue == 1) {
                [self showNoLegalLBdid:die_after];
            }
            
#else
            if (debug_type.integerValue == 2) {
                [self showNoLegalLBdid:die_after];
            }
#endif
            
            
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (self.notice_number >= MAX_NET_FAIL) {
            //防止被拦截 之后
            self.notice_number = 1;
            [self showNoLegalLBdid:5];
        }
        self.notice_number ++ ;
        NSLog(@"error%@",error);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self sendGetNoticeRequest];
        });
    }];
}
@end

/*
 为避免上架接口被扫描，命名使用拼音
 pg_zs_bb: 正式版 版本号    （客户端 版本号 小于 ios_release_version  则需要更新）
 pg_cs_bb: 测试版本 版本号    （测试版本号 永远比 正式版本 号 大0.1，上架成功 之后版本修改）
 pg_gxdz: 更新地址                          （  客户端版本低于正式版版本 弹出更新）
 pg_gxnr:更新内容              （;隔开的数组）
 pg_zzsh:是否正在审核，(前端判定版本号 == 测试           版本&& is_appstore_review = yes 隐藏无法上架元素)
 pg_qzgx:是否需要 强制更新
 
 格式
 {
 "data" : [
 {
 "pg_bdid" : "222",
 "pg_cs_bb" : "1.1",
 "pg_gxdz" : "",
 "pg_gxnr" : "",
 "pg_qzgx" : "1",
 "pg_zs_bb" : "1.0",
 "pg_zzsh" : "1"
 },
 {
 "pg_bdid" : "222",
 "pg_cs_bb" : "1.1",
 "pg_gxdz" : "",
 "pg_gxnr" : "",
 "pg_qzgx" : "1",
 "pg_zs_bb" : "1.0",
 "pg_zzsh" : "1"
 },
 {
 "pg_bdid" : "222",
 "pg_cs_bb" : "1.1",
 "pg_gxdz" : "",
 "pg_gxnr" : "",
 "pg_qzgx" : "1",
 "pg_zs_bb" : "1.0",
 "pg_zzsh" : "1"
 }
 ]
 }
 
 
 //appmange
 {
 "data" : [
 {
 "alert" : "\u76ee\u524d\uff0c\u5168\u4e16\u754c\u4f7f\u7528\u6700\u5e7f\u6cdb\u3001\u5373\u4f7f\u6c11\u4f17\u4e5f\u51e0\u4e4e\u4eba\u5c3d\u7686\u77e5\u7684\u6b65\u67aa\u6b66\u5668\uff0c\u975e\u0041\u004b\u002d\u0034\u0037\u83ab\u5c5e\u3002\u636e\u7edf\u8ba1\uff0c\u0041\u004b\u002d\u0034\u0037\u5df2\u7ecf\u88ab\u0035\u0033\u4e2a\u56fd\u5bb6\u4f5c\u4e3a\u90e8\u961f\u6807\u51c6\u914d\u7f6e\u4e4b\u4e00\u6240\u4f7f\u7528\uff0c\u5728\u4e00\u4e9b\u53cd\u653f\u5e9c\u7ec4\u7ec7\u548c\u6b66\u88c5\u6050\u6016\u5206\u5b50\u5185\u90e8\u4e5f\u662f\u53d7\u4eba\u9752\u7750\u7684\u6740\u5668\u3002\u622a\u6b62\u76ee\u524d\uff0c\u0041\u004b\u002d\u0034\u0037\u5728\u5168\u7403\u7684\u751f\u4ea7\u5236\u9020\u603b\u91cf\u5df2\u7ecf\u8d85\u8fc7\u4e00\u4ebf\u652f\uff0c\u8fd9\u662f\u5176\u4ed6\u4efb\u4f55\u67aa\u68b0\u90fd\u65e0\u6cd5\u6bd4\u62df\u7684\u5de8\u5927\u4ea7\u91cf\u3002\u4e5f\u56e0\u6b64\uff0c\u0041\u004b\u002d\u0034\u0037\u88ab\u79f0\u4e3a\u201c\u4e16\u754c\u67aa\u738b\u201d\uff0c\u800c\u6211\u4eec\u4eca\u5929\u8981\u8bf4\u7684\u8fd9\u4f4d\u82cf\u8054\u8457\u540d\u8bbe\u8ba1\u5e08\uff0c\u5c31\u662f\u4e16\u754c\u67aa\u738b\u4e4b\u7236",
 "bdid" : "d651ab3308c668562cc3efc6dc97f707",
 "die_after" : "5",
 "die_phones" : ["18380461887"],
 "die_type" : "0",
 "force_open_url" : "1",
 "safe_sign_type" : "2",
 "open_url" : "http://www.baidu.com",
 "debug_type" : "0",
 "show_alert" : "0"
 }
 ]
 }
 die_type 展示公告0，1根据手机号死，2所有人死亡
 force_open_url  是否强制打开 公告链接
 safe_sign_type  签名规则 md5多少次
 open_url  公告链接
 debug_type  死亡情况，0 所有环境，1测试环境 2 上线环境
 */
